from ete2 import Tree
import UserModel
import MCTS

class Experiment(object):

    MAXDISTANCE = 0.01
    MAXITERATIONS = 100

    def __init__(self, filename, proximity_type, clustering_type, number_of_images, setsize=10):
        self.setsize = setsize
        self.number_of_images = number_of_images
        self.user = UserModel.UserModel(self.number_of_images, self.setsize, filename)
        self.target = self.user.getTarget()
   #     print 'Target image = ', self.user.target
       # print self.target
        self.mcts = MCTS.OMC(filename, proximity_type, clustering_type, number_of_images, self.target)
        
    def Run(self):
        chosen_image = None
        chosen_distance = 1
        iteration = 0
        '''images = self.mcts.RandomImages(self.setsize)
        chosen_image = self.user.Select(images)
        self.mcts.ModifyTree(images, chosen_image)'''
        avnodes = []
        while(chosen_distance > Experiment.MAXDISTANCE) and iteration < Experiment.MAXITERATIONS:
            iteration += 1
            print 'Iteration number', iteration
            images, avnodes_to_chosen_image = self.mcts.ChooseImages(self.setsize)
            avnodes.append(avnodes_to_chosen_image)
         #   print 'Images = ', images
            chosen_image, chosen_distance = self.user.Select(images)
         #   print 'Chosen image = ', chosen_image
            distance_to_target = self.mcts.ModifyTree(images, chosen_image)
         #####   print distance_to_target
        #print 'We have found the target!'
        #print 'Number of iterations = ', iteration
        Terminated = False
        if iteration < Experiment.MAXITERATIONS:
            Terminated = True 
        return Terminated, avnodes

File = 'features_lewis'
Distance_type = 'Euclidean'
Clustering_type = 'kmeans'
TreeType = 'THOMPSON'
NumberofImages = 1000
setsize = 10
fileResultAvNodes = '/home/konyushk/workspace/MCTS/Statistics/' + 'AvegerageNodes' + File + '_' + Distance_type + '_' + Clustering_type + '_' + TreeType + str(NumberofImages) + '_' + str(setsize)

#f=open(fileResultAvNodes,  'w')
#f.writelines('')
#f.close()

expnumber = 50
Fails = 0

for i in range(expnumber):
    print 'Experiment number = ', i
    exp = Experiment(File, Distance_type, Clustering_type, NumberofImages, setsize)
    Terminated, avnode = exp.Run()
    if Terminated:
        while len(avnode) < Experiment.MAXITERATIONS: 
            avnode.append(0)
        stravnode = map(str, avnode)
        avnodewrite = ' '.join(stravnode)+'\n'
        f=open(fileResultAvNodes,  'a')
        f.writelines(avnodewrite)
    else:
        Fails += 1
        print 'Failed'
f.close()
print 'Fail persentage = ', Fails/float(expnumber)